package com.qin.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;

import cn.hutool.log.StaticLog;

/**
 * 用来处理字符集的Filter
 */
@WebFilter(filterName = "字符集Filter",urlPatterns = "/*"
	,initParams = {
			@WebInitParam(name = "charset",value = "utf-8") // 一些初始化参数
	})
public class CharsetFilter implements Filter {
	private String filterName;
	private String charset;
    /**
     * Default constructor. 
     */
    public CharsetFilter() {
    	
    }

	/**
	 * 销毁方法
	 */
	public void destroy() {
		StaticLog.debug("{} 被销毁", filterName);
	}

	/**
	 * 过滤方法，对字符集进行统一的设置
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		StaticLog.debug("{} Filter被调用", filterName);
		// 开始设置字符集
		request.setCharacterEncoding(charset);
		response.setCharacterEncoding(charset);
		
		chain.doFilter(request, response);
	}

	/**
	 * 初始化方法
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		filterName = fConfig.getFilterName();
		charset = fConfig.getInitParameter("charset");
	}

}
